<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="utf-8">
    <title>轨迹视角动画</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <style>
        body,
        html,
        #container {
            overflow: hidden;
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        .vue-container {
            position: fixed;
            top: 0;
            right: 10px;
            z-index: 9999;
        }
    </style>
    <script src="//mapopen.bj.bcebos.com/github/BMapGLLib/TrackAnimation/src/TrackAnimation.min.js"></script>
    <script src="//api.map.baidu.com/api?type=webgl&v=1.0&ak=7DCM7rFPzmiAjaMqj3PWb9YQgGb0BatY"></script>
    <script src="./vue.min.js"></script>
    <script src="./elementui.js"></script>
    <script src="./axios.min.js"></script>
    <link rel="stylesheet" href="./bootstrap.min.css">
    <link rel="stylesheet" href="./elementui.css">
    <link rel="stylesheet" href="./reserElement.css">
</head>

<body>
    <div id="container"></div>
    <div class="vue-container" id="v-container"></div>
</body>

</html>

<script>
    // window.app_base_url = 'http://127.0.0.1:9001'
    window.app_base_url = 'http://47.101.172.203:9001'
    var map = new BMapGL.Map("container", {
        displayOptions: {
            building: false,
        },
    });
    window.baiduMap = map
    map.centerAndZoom(new BMapGL.Point(114.009548, 33.013143), 17);
    map.enableScrollWheelZoom(true);
    var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
    map.addControl(scaleCtrl);
    var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
    map.addControl(zoomCtrl);
    // 禁用双击放大功能
    map.disableDoubleClickZoom();
    let lastLine = null;
    let marker = null
    // 定义查询轨迹是否返回数据初始值
    window.dataReturnStatus = false
    window.setInitPloyline = function (device_id, startTime) {
        window.dataReturnStatus = false
        axios({
            url: app_base_url + '/public/deviceLogTop20',
            method: 'post',
            data: { "device_id": device_id, "startTime": startTime },
        }).then(res => {
            if (res?.data?.data && res?.data?.data?.length > 0) {
                const data = res.data.data
                data.reverse()
                data.forEach((item, index) => {
                    const point = new BMapGL.Point(item.longitude, item.latitude);
                    if (index === 0) {
                        lastLine = point
                    } else {
                        polyline = new BMapGL.Polyline([point, lastLine],
                            lastLine = point,
                            // { strokeColor: "blue", strokeWeight: 3, strokeOpacity: 0.5 }
                        );
                        map.addOverlay(polyline);
                    }
                    if (index === data.length - 1) {
                        var myIcon = new BMapGL.Icon('./gezi59.png', new BMapGL.Size(32, 32));
                        marker = new BMapGL.Marker(point, { icon: myIcon });
                        map.addOverlay(marker);
                        map.setCenter(point);
                    }
                })
            }
            if (res?.data?.crawl && res?.data?.crawl?.length) {
                const crawl = res.data.crawl[0]
                const json_data = JSON.parse(crawl.json_data)
                if (json_data.command === 2 && window.__this.currentDevice === json_data._topic) {
                    const latitude = +json_data?.lat;
                    const longitude = +json_data?.lng;
                    const radiu = +json_data?.radiu;
                    if (!latitude || !longitude) return
                    if (window.pointCircle) {
                        map.removeOverlay(window.pointCircle);
                        window.pointCircle = null
                    }
                    window.pointCircle = new BMapGL.Circle(new BMapGL.Point(longitude, latitude), radiu, { strokeColor: "red", strokeWeight: 3, strokeOpacity: 1 });
                    map.addOverlay(window.pointCircle);
                    if (window.pointMarker) {
                        map.removeOverlay(window.pointMarker);
                        window.pointMarker = null
                    }
                    window.pointMarker = new BMapGL.Marker(new BMapGL.Point(longitude, latitude));
                    map.addOverlay(window.pointMarker);
                }
            }
            if (res?.data?.marks && res?.data?.marks?.length) {
                const marks = res.data.marks
                let json_data = marks.map(item => JSON.parse(item.json_data))
                const uniqueMap = new Map();
                // 遍历数组对象
                json_data.forEach(item => {
                    const key = item.lng.toString() + '|' + item.lat.toString();
                    if (!uniqueMap.has(key)) {
                        uniqueMap.set(key, item);
                    }
                });
                // 返回去重后的数组
                json_data = Array.from(uniqueMap.values());
                json_data.forEach(item => {
                    window.__setPonitBych(item)
                })
            }
            if(res?.data?.battery && res?.data?.battery?.length) {
                const battery = res.data.battery[0]
                console.log(battery);
                window.__this.voltage = battery?.voltage
                window.__this.volume = battery?.volume
            }
        }).catch(err => {
            alert(JSON.stringify('页面出错啦！', err))
        }).finally(() => {
            window.dataReturnStatus = true
        })
    }
    window.setInitPloyline('BIRDS_GNSS1', getFormattedDate())
    window.pointCircle = null
    window.pointMarker = null
    const ws = new WebSocket('ws://47.101.172.203:9002');
    // const ws = new WebSocket('ws://localhost:9002');
    window.wss = ws
    // 监听连接事件
    ws.onopen = () => {
        ws.send(JSON.stringify({ msg: 'hello server' }));
        console.log('ws连接成功');
    };
    // 监听消息事件
    ws.onmessage = (event) => {
        const data = JSON.parse(event.data)
        console.log('Received:', JSON.parse(event.data));
        // // 解析数据
        // var latitude = data.lat / 1000000;
        // var longitude = data.lng / 1000000;
        var latitude = +data?.params?.Latitude;
        var longitude = +data?.params?.Longitude;
        var voltage = data?.params?.voltage; // 电压
        var volume = data?.params?.volume; // 电量
        var c_topic = data?._topic
        if (data.ID === 'GeoLocation') {
            if (latitude && longitude && window.__this.currentDevice === c_topic) {
                const dddd = [...window.__this.devicee.deviceMsg, {
                    info0: `设备ID：${c_topic}`,
                    info1: `更新时间：${new Date().toLocaleString()}`,
                    info2: `经度：${longitude}`,
                    info3: `纬度：${latitude}`,
                }];
                window.__this.$set(window.__this.devicee, 'deviceMsg', dddd)
                // 如果轨迹点请求数据没返回就不展示轨迹信息！！！！
                if (!window.dataReturnStatus) return
                // 更新地图标记点
                var point = new BMapGL.Point(longitude, latitude);
                // 绘制轨迹线
                if (lastLine) {
                    map.removeOverlay(marker);
                    var myIcon = new BMapGL.Icon('./gezi59.png', new BMapGL.Size(32, 32));
                    marker = new BMapGL.Marker(point, { icon: myIcon });
                    // map.addOverlay(marker);
                    var polyline = new BMapGL.Polyline([point, lastLine],
                        lastLine = point,
                        // { strokeColor: "blue", strokeWeight: 3, strokeOpacity: 0.5 }
                    );
                    // console.log(point);
                    map.addOverlay(marker); // 添加标注到地图
                    map.setCenter(point); // 地图中心移动到该点
                    map.addOverlay(polyline);

                } else {
                    console.log('第一个轨迹点');
                    // marker = new BMapGL.Marker(point);
                    lastLine = point;
                    var myIcon = new BMapGL.Icon('./gezi59.png', new BMapGL.Size(32, 32));
                    marker = new BMapGL.Marker(point, { icon: myIcon });
                    map.addOverlay(marker);
                    map.setCenter(point);
                }
                window.lastMarker = marker
            } else {
                console.log('无效GPS数据');
            }
        } else if (data.ID === 'BATTERY') {
            if (voltage && volume && window.__this.currentDevice === c_topic) {
                const dddd = [...window.__this.devicee.deviceMsg, {
                    info0: `设备ID：${c_topic}`,
                    info1: `更新时间：${new Date().toLocaleString()}`,
                    info2: `电压：${voltage}`,
                    info3: `电量：${volume}`,
                }];
                window.__this.$set(window.__this.devicee, 'deviceMsg', dddd)
                window.__this.voltage = voltage
                window.__this.volume = volume
            } else {
                console.log('无效电池数据')
            }
        } else {
            if (data.command === 2 && window.__this.currentDevice === c_topic) {
                const latitude = +data?.lat;
                const longitude = +data?.lng;
                const radiu = +data?.radiu;
                if (!latitude || !longitude) return
                if (window.pointCircle) {
                    map.removeOverlay(window.pointCircle);
                    window.pointCircle = null
                }
                window.pointCircle = new BMapGL.Circle(new BMapGL.Point(longitude, latitude), radiu, { strokeColor: "red", strokeWeight: 3, strokeOpacity: 1 });
                map.addOverlay(window.pointCircle);
                if (window.pointMarker) {
                    map.removeOverlay(window.pointMarker);
                    window.pointMarker = null
                }
                window.pointMarker = new BMapGL.Marker(new BMapGL.Point(longitude, latitude));
                map.addOverlay(window.pointMarker);
            } else {
                console.log('不是当前设备');
            }
            // console.log(data);
        }
        if (data?.command === 1) {
            window.__setPonitBych(data)
        }
        // window.__setPonitBych = function () {
        //     var point = new BMapGL.Point(longitude, latitude);
        //     var myIcon = new BMapGL.Icon('./map_marker.png', new BMapGL.Size(32, 32));
        //     const marker = new BMapGL.Marker(point, { icon: myIcon });
        //     map.addOverlay(marker);
        // }
    };
    window.__setPonitBych = function (data) {
        const latitude = data.lat
        const longitude = data.lng
        if (!latitude || !longitude) return
        var point = new BMapGL.Point(longitude, latitude);
        var myIcon = new BMapGL.Icon('./map_marker.png', new BMapGL.Size(32, 32));
        const marker = new BMapGL.Marker(point, { icon: myIcon });
        map.addOverlay(marker);
    }
    // 监听关闭事件
    ws.onclose = () => {
        console.log('ws连接关闭');
    };
    function getFormattedDate() {
        // 创建一个Date对象
        var today = new Date();
        // 获取年、月、日
        var year = today.getFullYear();
        var month = today.getMonth() + 1; // 月份是从0开始的
        var day = today.getDate();
        // 补零函数
        function padTo2Digits(num) {
            return num.toString().padStart(2, '0');
        }
        // 返回格式化的日期
        return `${year}-${padTo2Digits(month)}-${padTo2Digits(day)} 00:00:00`;
    }
</script>
<script src="./insertPage.js"></script>